package nl.hanze.designpatterns.DAO.impl.file.crypted;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import nl.hanze.designpatterns.domain.LoginCredential;

public class CryptedInputStream {
	private ObjectInputStream ois;
	static String IV = "AAAAAAAAAAAAAAAA";
	static String encryptionKey = "0123456789abcdef";
	
	//create CryptedInputStream
	public CryptedInputStream(FileInputStream fi){
		try {
			ois = new ObjectInputStream(fi);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public Object getObject() throws ClassNotFoundException, IOException{
		LoginCredential lc = (LoginCredential) ois.readObject();
		return lc;
	}
	
	public Object bytesToObject(byte[] bytes) throws IOException, ClassNotFoundException{
		ByteArrayInputStream b = new ByteArrayInputStream(bytes);
    	ObjectInputStream o = new ObjectInputStream(b);
        return o.readObject();
	}
	
	
	
	 public String decrypt(byte[] input, String passkey) throws Exception{
	        Cipher cipher = Cipher.getInstance("AES/CBC/ISO10126Padding");
	        SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
	        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(new byte[cipher.getBlockSize()]));
	        String plainText = new String(cipher.doFinal(input));
	        return plainText;
	    }
}
